package com.readfeed.app;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.readfeed.app.adapter.FeedsListAdapter;
import com.readfeed.app.data.FeedsAdapter;
import com.readfeed.app.fragment.ErrorDialogFragment;
import com.readfeed.app.fragment.ProgressDialogFragment;
import com.readfeed.app.model.Feed;
import com.readfeed.app.utils.Utilities;

public class FeedsListActivity extends Activity {
	
	public static final String FEED_ID_EXTRA = "feed";
	private static final String DELETE_FEED_MESSAGE = "Feeds deleted";
	
	
	private String mChannelUrl;
	private long mChannelLastUpdate;
	private long mChannelId;
	private boolean mIsConnected;
	private FeedsAdapter mFeedAdapter;
	private FeedsListAdapter mListAdapter;
	private ListView mListView;	
	private FragmentManager mFragmentManager;
	private long mUpdatePeriod;
	private long mDiscardPeriod;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_feeds_list);
		// Show the Up button in the action bar.
		setupActionBar();			
		mFeedAdapter = new FeedsAdapter(this);
		mFeedAdapter.open();
		mFragmentManager = getFragmentManager();
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		this.convertPreferenceValues(sharedPrefs);
		mIsConnected = this.checkConnectivity();
		
		mChannelLastUpdate = getIntent().getExtras().getLong(ChannelsListActivity.CHANNEL_UPDATE_EXTRA);
		mChannelId = getIntent().getExtras().getLong(ChannelsListActivity.CHANNEL_ID_EXTRA);
		mChannelUrl = getIntent().getExtras().getString(ChannelsListActivity.CHANNEL_URI_EXTRA);
		
		this.updateChannel();		
		
		mListView = (ListView) findViewById(R.id.feeds_list_view);				
		this.configureListView();					
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		this.fillData();
	}
	
	private void updateChannel(){
		UpdateChannelTask updateTask = new UpdateChannelTask(this, mDiscardPeriod, mUpdatePeriod,
				mChannelLastUpdate, mChannelId, mChannelUrl, mFeedAdapter, mIsConnected);
		updateTask.execute();
	}
	
	private void convertPreferenceValues(SharedPreferences sharedPreferences){
		mUpdatePeriod = Long.parseLong(sharedPreferences.getString(PreferencesActivity.UPDATE_ITEMS_PREF_KEY, ""));
		mDiscardPeriod = Long.parseLong(sharedPreferences.getString(PreferencesActivity.DISCARD_ITEMS_PREF_KEY, ""));
		
		if (mDiscardPeriod != -1) {
			mDiscardPeriod *= (60*60000);
		}
		
		if (mUpdatePeriod != -1) {
			mUpdatePeriod *= 60000;
		}
	}
	
	private boolean checkConnectivity(){
		ConnectionDetector detector = new ConnectionDetector(this);
		return detector.isConnectingToInternet();
	}
	
	private void configureListView(){
		mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		mListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
			
		private int selectedCount;
			
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {	
			selectedCount = 0;
        	List<Feed> feeds = mListAdapter.getSelectedFeeds();
        	if (feeds.size() != 0) {				
				switch (item.getItemId()) {                
		            case R.id.feed_action_delete:                           
		                deleteFeeds(feeds);
		                mListAdapter.removeSelectedFeeds();
		                mListAdapter.clearSelection();
		                mode.finish();
		                break;
		                
		            case R.id.action_share:
		            	String url = feeds.get(0).getUrl();
		            	Intent shareIntent = new Intent();
		            	shareIntent.setAction(Intent.ACTION_SEND);
		            	shareIntent.putExtra(Intent.EXTRA_TEXT, url);
		            	shareIntent.setType("text/plain");
		            	startActivity(shareIntent);
		            	
		            	mode.finish();
		            	break;
		            default:
						break;
				}
        	} else {
        		Toast.makeText(FeedsListActivity.this, Utilities.NO_ITEMS_SELECTED_MESSAGE, Toast.LENGTH_SHORT).show();
        	}
						
			return false;
		}										

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {			
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.feed_context_menu, menu);
			
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mListAdapter.clearSelection();
			
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			if (selectedCount > 1) {
				MenuItem shareItem = menu.findItem(R.id.action_share);
				shareItem.setVisible(false);
			} else {
				MenuItem shareItem = menu.findItem(R.id.action_share);
				shareItem.setVisible(true);
			}
			
			return true;
		}

		@Override
		public void onItemCheckedStateChanged(ActionMode mode,
				int position, long id, boolean checked) {			
				 if (checked) {
					 selectedCount++;
				     mListAdapter.setNewSelection(position, checked);                    
				 } else {
					 selectedCount--;
				     mListAdapter.removeSelection(position);                 
				 }
				 
				 mode.setTitle(selectedCount + " items selected");
				 mode.invalidate();
			}
		});
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Feed clickedItem = mListAdapter.getFeedByPosition(position);
				long feedId = clickedItem.getId();				
				
				Intent intent = new Intent(FeedsListActivity.this, FeedItemActivity.class);
				intent.putExtra(FEED_ID_EXTRA, feedId);				
				startActivity(intent);				
			}
			
		});
	}
	
	private void fillData(){
		FillDataTask fillDataTask = new FillDataTask();
		fillDataTask.execute(mChannelId);
	}
	
	@SuppressWarnings("unchecked")
	private void deleteFeeds(List<Feed> feedsToDelete){
		DeleteFeedsTask deleteTask = new DeleteFeedsTask();
		deleteTask.execute(feedsToDelete);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		String title = getIntent().getExtras().getString(ChannelsListActivity.CHANNEL_TITLE_EXTRA);
		
		actionBar.setTitle(title);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.feeds_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//TODO create refresh action
		switch (item.getItemId()) {
			case android.R.id.home:
				NavUtils.navigateUpFromSameTask(this);
				return true;
			case R.id.feeds_action_settings:
				Intent prefIntent = new Intent(FeedsListActivity.this, PreferencesActivity.class);
				startActivity(prefIntent);			
				return true;	
			case R.id.action_refresh_channel:
				this.updateChannel();
				break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private class FillDataTask extends AsyncTask<Long, Void, List<Feed>>{
		private Exception ex = null;
		
		List<Feed> feeds = new ArrayList<Feed>();
		@Override
		protected List<Feed> doInBackground(Long... channelId) {
			long id = channelId[0];
			try {
				feeds = mFeedAdapter.getFeedsByChannelId(id);
			} catch (ParseException e) {
				this.ex = e;
			}
			
			return feeds;
		}
		
		@Override
		protected void onPostExecute(List<Feed> result) {
			if (ex != null) {
				ErrorDialogFragment errorDialog = ErrorDialogFragment.newInstance(R.string.error_loading_feeds);
				errorDialog.show(mFragmentManager, Utilities.ERROR_DIALOG_TAG);
			} else {
				mListAdapter = new FeedsListAdapter(FeedsListActivity.this, R.layout.feed_row, result);
				mListView.setAdapter(mListAdapter);
			}
		}		
	}
	
	private class DeleteFeedsTask extends AsyncTask<List<Feed>, Void, Void>{

		@Override
		protected void onPreExecute() {
			ProgressDialogFragment progressDialog = ProgressDialogFragment.newInstance(
					R.string.progress_dialog_loading);
			progressDialog.show(getFragmentManager(), Utilities.PROGRESS_DIALOG_TAG);
		}
		
		@Override
		protected Void doInBackground(List<Feed>... feeds) {
			List<Feed> feedsList = feeds[0];
			mFeedAdapter.deleteFeeds(feedsList);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			ProgressDialogFragment fr = ((ProgressDialogFragment)getFragmentManager().findFragmentByTag(Utilities.PROGRESS_DIALOG_TAG));
			if (fr != null) {
				fr.dismiss();
			}
						
			Toast.makeText(FeedsListActivity.this, DELETE_FEED_MESSAGE, Toast.LENGTH_LONG).show();
		}
	}
}